package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.PersonalScoreListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.PersonScore;
import com.isunland.managesystem.entity.PersonalScoreList;
import com.isunland.managesystem.entity.PersonalScoreList.PersonalScoreContent;
import com.isunland.managesystem.entity.PersonalUseableScore;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/22.
 * 员工奖惩积分填报列表
 */
public class StaffScoreFillListFragment extends BaseListFragment {

  private TextView tvContent1;
  private TextView tvTitle1;
  private TextView tvContent2;
  private TextView tvTitle2;
  private TextView tvContent3;
  private TextView tvTitle3;

  private static final int REQUEST_ADD = 0;
  private static final int REQUEST_DETAIL = 1;
  private static final int REQUEST_QUERY = 2;
  private String mStartDate;
  private String mEndDate;
  private PersonalScoreListAdapter mAdapter;
  private int mPage = 1;// 请求第几页的数据
  private String mDataStatus;//数据状态

  @Override public void onStart() {
    VolleyPostGetScore();
    super.onStart();
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.personScoreFill);
    mEndDate = MyDateUtil.dateToString(MyDateUtil.getAfterDay(new Date(), 1), MyDateUtil.TYPE_DATE);
    mStartDate = MyDateUtil.dateToString(MyDateUtil.getBeforeMonth(1), MyDateUtil.TYPE_DATE);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.view_rew_score, null, false);
    tvTitle1 = (TextView) header.findViewById(R.id.tv_title1);
    tvContent1 = (TextView) header.findViewById(R.id.tv_content1);
    tvTitle2 = (TextView) header.findViewById(R.id.tv_title2);
    tvContent2 = (TextView) header.findViewById(R.id.tv_content2);
    tvTitle3 = (TextView) header.findViewById(R.id.tv_title3);
    tvContent3 = (TextView) header.findViewById(R.id.tv_content3);
    tvTitle1.setText("剩余可派奖励分");
    tvTitle2.setText("剩余可派惩罚分");
    tvTitle3.setText("本月已派分值");
    tvContent3.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
    tvContent3.getPaint().setAntiAlias(true);//抗锯齿
    tvContent3.setVisibility(View.VISIBLE);
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    tvContent3.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        Intent intent = new Intent(getActivity(), ScoreMonthListActivity.class);
        intent.putExtra(ScoreMonthListFragment.EXTRA_PAYID, mCurrentUser.getJobNumber());
        startActivity(intent);
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_GETE_FILL_SCOR;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("page", mPage + "");
    params.put("pageSize", "20");
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("payStaffId", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("beginregDate", mStartDate);
    params.put("endregDate", mEndDate);
    params.put("orderSeq", "desc");
    params.put("orderField", "reg_date");

    if (TextUtils.isEmpty(mDataStatus)) {
      params.put("dataStatus", "");
    } else {
      params.put("dataStatus", mDataStatus);
    }

    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    PersonalScoreList staffScore = new Gson().fromJson(json, PersonalScoreList.class);
    List<PersonalScoreContent> detail = staffScore.getRows();
    if (detail != null && detail.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(detail);
  }

  private void setAdapter(List<PersonalScoreContent> detail) {
    if (detail == null) {
      detail = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter =
          new PersonalScoreListAdapter(getActivity(), detail, PersonalScoreListAdapter.ASSIGN);
      setListAdapter(mAdapter);
      return;
    }

    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(detail);
    ((PersonalScoreListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_add_search, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //避免点击header时的getitem出现-1的情况.
    if (position < mListview.getHeaderViewsCount()) return;
    PersonalScoreContent content = mAdapter.getItem(position - l.getHeaderViewsCount());
    if (content == null) return;
    Intent intent;
    if (DataStatus.PUBLIS.equalsIgnoreCase(content.getDataStatus())
        || DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())) {
      intent = new Intent(getActivity(), PersonalScoreDetailActivity.class);
      intent.putExtra(PersonalScoreDetailFragment.EXTRA_VALUE, content);
      intent.putExtra(PersonalScoreDetailFragment.EXTRA_TYPE, PersonalScoreDetailFragment.ASSIGN);
      intent.putExtra(PersonalScoreDetailFragment.EXTRA_FROM, PersonalScoreDetailFragment.FILL);
    } else {
      intent = new Intent(getActivity(), StaffScoreAddDetailActivity.class);
      intent.putExtra(StaffScoreAddDetailFragment.EXTRA_VALUE, content);
    }
    startActivityForResult(intent, REQUEST_DETAIL);
    super.onListItemClick(l, v, position, id);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:
        getActivity().finish();
        break;
      case R.id.menu_item_add:
        intent = new Intent(getActivity(), StaffScoreAddActivity.class);
        startActivityForResult(intent, REQUEST_ADD);
        break;
      case R.id.menu_item_querys:
        intent = new Intent(getActivity(), PersonalScoreSearchActivity.class);
        intent.putExtra(PersonalScoreSearchFragment.REQUEST_START, mStartDate);
        intent.putExtra(PersonalScoreSearchFragment.REQUEST_END, mEndDate);
        intent.putExtra(PersonalScoreSearchFragment.REQUEST_DATASTATUS, mDataStatus);
        startActivityForResult(intent, REQUEST_QUERY);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 获取所剩余可派奖励分、剩余可派惩罚分
   */
  protected void VolleyPostGetScore() {
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("staffId", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("dataStatus", "publish");
    params.put("currentYearMonth", MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE4));
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_GET_ALL_SCORE);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        PersonalUseableScore useableScore = new Gson().fromJson(arg0, PersonalUseableScore.class);
        if (useableScore != null) {
          String mUsabeAddScore = useableScore.getCurrentRewvalue();//可派奖励分
          String mUsablePlusScore = useableScore.getCurrentPunvalue();//可派惩罚分
          String mCownyearSumvalue = useableScore.getCownyearSumvalue();//本月已派分值
          tvContent1.setText(mUsabeAddScore);
          tvContent2.setText(mUsablePlusScore);
          tvContent3.setText(mCownyearSumvalue);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_ADD) {
      volleyPost();
      return;
    }

    if (requestCode == REQUEST_QUERY && data != null) {
      PersonScore mScoreSearch =
          (PersonScore) data.getSerializableExtra(PersonalScoreSearchFragment.REQUEST_SEARCH);
      mStartDate = mScoreSearch.getStartDate();
      mEndDate = mScoreSearch.getEndDate();
      mDataStatus = mScoreSearch.getDataStatus();
      volleyPost();
      return;
    }
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    PullToRefreshBase.Mode mode = refreshView.getCurrentMode();
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
      mPage = 1;
    }
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }
}
